package demo.thread;

/**
 * 多线程模拟一个存 一个取，最终保证余额正确
 */
public class CQDemo {
     
    public static void main(String[] args) {
         
        final ATM business = new ATM(1000);
        new Thread(new Runnable(){
           public void run() {
        	   for(int i=0;i<10;i++){
                   business.deposit();
               }
           }
        }).start();
        new Thread(new Runnable(){
            public void run() {
            	for(int i=0;i<10;i++){
                    business.withdraw();
                }
            }
        }).start(); 
         
    }
}
class ATM{
    int balance = 1000;
    boolean isWithdraw = false;
    
    public ATM(int balance){
        this.balance = balance;
    }
    
    public synchronized void deposit(){
        if(isWithdraw){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        balance = balance+300;
        System.out.println(Thread.currentThread().getName()+ " 存款 $300,现在的余额：" + balance);
        isWithdraw=true;
        this.notify();
         
    }
    public synchronized void withdraw(){
        if(!isWithdraw){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if(balance>0){
        	balance = balance-300;
        	System.out.println(Thread.currentThread().getName()+ " 取款 $300,现在的余额:" + balance);
        } 
        isWithdraw=false;
        this.notify();
    }
}